Expand description

Simple usage

Creating the server

The easiest way to create a server is to call Server::http().

The http() function returns an IoResult<Server> which will return an error in the case where the server creation fails (for example if the listening port is already occupied).

let server = tiny_http::Server::http("0.0.0.0:0").unwrap();

A newly-created Server will immediately start listening for incoming connections and HTTP requests.

Receiving requests

Calling server.recv() will block until the next request is available. This function returns an IoResult<Request>, so you need to handle the possible errors.


loop {
    // blocks until the next request is received
    let request = match server.recv() {
        Ok(rq) => rq,
        Err(e) => { println!("error: {}", e); break }
    };

    // do something with the request
    // ...
}

In a real-case scenario, you will probably want to spawn multiple worker tasks and call server.recv() on all of them. Like this:

let server = Arc::new(server);
let mut guards = Vec::with_capacity(4);

for _ in (0 .. 4) {
    let server = server.clone();

    let guard = thread::spawn(move || {
        loop {
            let rq = server.recv().unwrap();

            // ...
        }
    });

    guards.push(guard);
}

If you don’t want to block, you can call server.try_recv() instead.

Handling requests

The Request object returned by server.recv() contains informations about the client’s request. The most useful methods are probably request.method() and request.url() which return the requested method (GET, POST, etc.) and url.

To handle a request, you need to create a Response object. See the docs of this object for more infos. Here is an example of creating a Response from a file:

let response = tiny_http::Response::from_file(File::open(&Path::new("image.png")).unwrap());

All that remains to do is call request.respond():

let _ = request.respond(response);

Structs

HTTP version (usually 1.0 or 1.1).
Represents a HTTP header.
Field of a header (eg. Content-Type, Content-Length, etc.)
Represents an HTTP request made by a client.
Object representing an HTTP response whose purpose is to be given to a Request.
The main class of this library.
Represents the parameters required to create a server.
Configuration of the server for SSL.
Status code of a request or response.
A simpler version of Request that is useful for testing. No data actually goes anywhere.

Enums

Unified listen socket address. Either a SocketAddr or std::os::unix::net::SocketAddr.
HTTP request methods

Traits

Dummy trait that regroups the Read and Write traits.

Type Definitions

A Response without a template parameter.